import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Image,
  Modal,
  Tooltip,
  Radio,
  Row,
  Col,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  show_img_url,
  kind_status,
  key_find_obj,
  random_string,
} from "../../utils";

export default function VisionNchGoods(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { Option } = Select;
  const { Group } = Radio;
  const { confirm } = Modal;
  const { actions, setSpinning } = props;

  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [name_search, setName_search] = useState("");
  const [barcode_search, setBarcode_search] = useState("");
  const [status, setStatus] = useState("");
  const [goods_list, setGoods_list] = useState([]);

  const getData = async (newPage, newRows, newBar_lib) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      barcode: barcode_search,
      name: name_search,
      status: status,
    };
    setSpinning(true);
    let res = await post_axios("vision_mch_goods", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    const receiveRows = res.data_rows.rows.map((item) => {
      item["pic"] = show_img_url(item, local_company_object.company);
      return item;
    });
    setGoods_list(receiveRows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.goods_name"),
      dataIndex: "name",
      align: "center",
    },
    {
      title: t("goods.goods_barcode"),
      dataIndex: "barcode",
      align: "center",
    },
    {
      title: t("goods.goods_brand"),
      align: "center",
      width: 100,
      render: (_, record) => (
        <>
          {
            key_find_obj(record.brand, goods_brand_list, "brand_number")
              .brand_name
          }
        </>
      ),
    },
    {
      title: t("operate.price"),
      align: "center",
      width: 100,
      render: (_, record) => (
        <>
          {record.price ? <span>{(record.price / 100.0).toFixed(2)}</span> : ""}
        </>
      ),
    },

    {
      title: t("goods.vision_alipay_ok"),
      dataIndex: "alipay_ok",
      width: 100,
      align: "center",
    },

    {
      title: t("goods.vision_cloudwalk_ok"),
      dataIndex: "cloudwalk_ok",
      width: 100,
      align: "center",
    },
    {
      title: t("goods.goods_image"),
      align: "center",
      render: (_, record) => (
        <>
          {record.pic && record.pic.length !== 0 ? (
            <Image className="table_img" src={record.pic} />
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: t("goods.code_cloudwalk"),
      align: "center",
      ellipsis: true,
      render: (_, record) => (
        <div>
          <Tooltip title={record.code_cloudwalk} color="blue">
            <div style={{ cursor: "pointer" }}>{record.code_cloudwalk}</div>
          </Tooltip>
          <br />
          <Tooltip title={record.barcode_cloudwalk} color="blue">
            <div style={{ cursor: "pointer" }}>{record.barcode_cloudwalk}</div>
          </Tooltip>
        </div>
      ),
    },
    {
      title: t("goods.code_alipay"),
      align: "center",
      ellipsis: true,
      render: (_, record) => (
        <div>
          <Tooltip title={record.code_alipay} color="blue">
            <div style={{ cursor: "pointer" }}>{record.code_alipay}</div>
          </Tooltip>
          <br />
          <Tooltip title={record.barcode_alipay} color="blue">
            <div style={{ cursor: "pointer" }}>{record.barcode_alipay}</div>
          </Tooltip>
        </div>
      ),
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.barcode);
    setclickRow(row);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    getData(page, rows);
  };

  // 获取品牌信息
  const [options_brand, setOptions_brand] = useState();
  const [goods_brand_list, setGoods_brand_list] = useState([]);
  const get_goods_brand = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("brand", "m_query", upMsg);
    if (!res) return;
    const rows = res.data_rows.rows;
    setGoods_brand_list(rows);
    let newOptions = [];
    for (let i = 0; i < rows.length; i++) {
      newOptions.push({
        value: rows[i].brand_number,
        label: rows[i].brand_name,
        key: rows[i].brand_number,
      });
    }
    console.log(newOptions);
    setOptions_brand(newOptions);
  };

  const [radio_goods_kind, setRadio_goods_kind] = useState("alipay"); // 选择总库按钮
  const [bar_lib, setBar_lib] = useState("");
  const [vision_name_search, setVision_name_search] = useState(""); // 算法库名称模糊查询
  const [vision_barcode_search, setVision_barcode_search] = useState(""); // 算法库国标码模糊查询
  const [goods_kind_page, setGoods_kind_page] = useState(1); // 外部库商品页码
  const [goods_kind_rows, setGoods_kind_rows] = useState(20); // 外部库每页数量
  const [goods_kind_total, setGoods_kind_total] = useState(0); // 外部库商品总数
  const [vision_all_goods_list, setVision_all_goods_list] = useState([]); // 外部商品总库

  // 查询总库
  const query_goods_kind = async (newPage, newRows, newType) => {
    console.log(newType);
    let upMsg = {
      page: newPage ? newPage : goods_kind_page,
      rows: newRows ? newRows : goods_kind_rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      bar_lib: bar_lib,
      name_search: vision_name_search,
      barcode_search: vision_barcode_search,
    };
    let action = "";
    const type = newType ? newType : radio_goods_kind;
    switch (type) {
      case "cloudwalk":
        action = "m_query_cw";
        break;
      case "alipay":
      default:
        action = "m_query_alipay";
        break;
    }
    setSpinning(true);
    let res_goods = await post_axios("vision_mch_goods", action, upMsg);
    setSpinning(false);
    if (res_goods) {
      const newGoodsList = res_goods.data_rows.rows.map((item) => {
        item["pic_show"] = show_img_url(item, local_company_object.company);
        return item;
      });
      setVision_all_goods_list(newGoodsList);
      setGoods_kind_total(res_goods.data_rows.total);
    }
  };
  // 分页器
  const kindPageOnChange = async (page, pageSize) => {
    setGoods_kind_page(page);
    setGoods_kind_rows(pageSize);
    initData(page, pageSize);
  };
  const listMatchSetValue = (value, index, key) => {
    const newList = JSON.parse(JSON.stringify(list_match));
    newList[index][key] = value;
    setList_match(newList);
  };
  const listMatchColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.goods_barcode"),
      align: "center",
      render: (_, record, index) => (
        <>
          <Input
            className="mini_input"
            defaultValue={record.barcode}
            value={record.barcode}
            onChange={(e) =>
              listMatchSetValue(e.target.value, index, "barcode")
            }
            size="small"
          />
        </>
      ),
    },
    {
      title: t("goods.goods_name"),
      align: "center",
      render: (_, record, index) => (
        <>
          <Input
            className="mini_input"
            defaultValue={record.name}
            value={record.name}
            onChange={(e) => listMatchSetValue(e.target.value, index, "name")}
            size="small"
          />
        </>
      ),
    },
    {
      title: t("goods.goods_image"),
      align: "center",
      render: (_, record) => (
        <>
          {record.pic && record.pic.length !== 0 ? (
            <Image className="table_img" src={record.pic} />
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: t("operate.price"),
      align: "center",
      render: (_, record, index) => (
        <>
          <Input
            className="mini_input"
            defaultValue={record.price}
            value={record.price}
            onChange={(e) => listMatchSetValue(e.target.value, index, "price")}
            size="small"
          />
        </>
      ),
    },
    {
      title: t("goods.name_alipay"),
      align: "center",
      children: [
        {
          title: t("goods.code_alipay"),
          align: "center",
          render: (_, record, index) => (
            <div className="breakText">
              {record.name_alipay}
              <br />
              {record.code_alipay}
            </div>
          ),
        },
      ],
    },
    {
      title: t("goods.name_cloudwalk"),
      align: "center",
      children: [
        {
          title: t("goods.code_cloudwalk"),
          align: "center",
          render: (_, record, index) => (
            <div className="breakText">
              {record.name_cloudwalk}
              <br />
              {record.code_cloudwalk}
            </div>
          ),
        },
      ],
    },
    {
      title: t("goods.goods_brand"),
      align: "center",
      render: (_, record, index) => (
        <>
          <Select
            style={{ width: "200px" }}
            defaultValue={record.brand}
            onChange={(value) => listMatchSetValue(value, index, "brand")}
            size="small"
            options={options_brand}
          />
        </>
      ),
    },
    {
      title: "操作",
      align: "center",
      render: (_, record, index) => (
        <>
          <Button type="primary" onClick={() => delete_match(record, index)}>
            {t("common.delete")}
          </Button>
        </>
      ),
    },
  ];

  const visionGoodsColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("goods.goods_name"),
      align: "center",
      dataIndex: "name",
    },
    {
      title: t("goods.goods_image"),
      align: "center",
      render: (_, record) => (
        <>
          {record.pic && record.pic.length !== 0 ? (
            <Image className="table_img" src={record.pic} />
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: t("goods.goods_barcode"),
      align: "center",
      render: (_, record, index) => (
        <div className="breakText">
          {radio_goods_kind == "alipay" ? (
            <span>
              {record.code_alipay}
              <br />
              {record.barcode}
            </span>
          ) : (
            <span>
              {record.code_cloudwalk}
              <br />
              {record.barcode}
            </span>
          )}
        </div>
      ),
    },
  ];

  const choose_goods_search = async () => {
    setGoods_kind_page(1);
    query_goods_kind(1, goods_kind_rows);
  };

  const [choose_goods_show, setChoose_goods_show] = useState(false);
  const [list_match, setList_match] = useState([]); // 支付宝云从商品绑定展示
  const [choose_match_index, setChoose_match_index] = useState(-1); // 当前处理的绑定条目序号
  const add_goods_dialog_show = async () => {
    setList_match([]);
    setChoose_match_index(-1);
    setVision_name_search("");
    setVision_barcode_search("");
    await choose_goods_kind_init("alipay");
    setChoose_goods_show(true);
  };

  // 外部总库选择切换 alipay/cloudwalk
  const choose_goods_kind_init = (radio_name) => {
    setRadio_goods_kind(radio_name);
    setVision_all_goods_list([]);
    setGoods_kind_page(1); // 外部库商品页码
    query_goods_kind(1, goods_kind_rows, radio_name);
  };

  // 匹配列表的单行选中事件
  const handle_match_row_click = (row) => {
    setChoose_match_index(list_match.indexOf(row));
    console.log("选中行:", choose_match_index, row);
  };

  // 添加新行来匹配支付宝和云从商品
  const add_match_goods = () => {
    let item_add = {
      name: "",
      barcode: "",
      name_alipay: "",
      name_cloudwalk: "",
      code_alipay: "",
      code_cloudwalk: "",
      opt: "",
      key: random_string(8),
    };
    setList_match([...list_match, item_add]);
  };

  const add_row_click = () => {
    if (list_match.length <= 0) {
      setChoose_match_index(-1);
    }
    add_match_goods();
  };

  // 点击选择总库商品云从+支付宝
  const row_click_goods_base = (item) => {
    let matchIdx = 0;
    let item_match = {};
    if (list_match.length <= 0) {
      matchIdx = 0;
      add_match_goods();
      item_match = {
        name: "",
        barcode: "",
        name_alipay: "",
        name_cloudwalk: "",
        code_alipay: "",
        code_cloudwalk: "",
        opt: "",
        key: random_string(8),
      };
    } else {
      matchIdx = choose_match_index;
      item_match = list_match[matchIdx];
    }
    console.log(item_match);
    switch (radio_goods_kind) {
      case "alipay":
        let ali_has_checked = list_match.filter((match) => {
          return match.code_alipay === item.code_alipay;
        });
        if (ali_has_checked.length >= 1) {
          message.warning({
            content: "请勿重复设置该商品",
          });
          return;
        }
        item_match.barcode = item.barcode[0];
        item_match.name = item.name;
        item_match.code_alipay = item.code_alipay;
        item_match.name_alipay = item.name;
        item_match.barcode_alipay = item.barcode;
        item_match.pic = item.pic_show;
        item_match.pic_alipay = item.pic_show;
        break;
      case "cloudwalk":
        let cw_has_checked = list_match.filter((match) => {
          return match.code_cloudwalk === item.code_cloudwalk;
        });
        if (cw_has_checked.length >= 1) {
          message.warning({
            content: "请勿重复设置该商品",
          });
          return;
        }

        if (!item_match.barcode_alipay) {
          // 如果支付宝视觉编码已存在，代表已经选择过支付宝商品，选择云从商品不替换条码、名称、图片
          item_match.barcode = item.barcode[0]; // 优先支付宝的国标码
          item_match.name = item.name; // 优先支付宝的名称
          item_match.pic = item.pic_show; // 优先支付宝的图片
        }
        item_match.pic_cloudwalk = item.pic_show;
        item_match.code_cloudwalk = item.code_cloudwalk;
        item_match.name_cloudwalk = item.name;
        item_match.barcode_cloudwalk = item.barcode;
        break;
      default:
        item.barcode = "不支持";
    }
    const newList = JSON.parse(JSON.stringify(list_match));
    console.log(newList);
    newList[matchIdx] = item_match;
    console.log(newList);
    setList_match(newList);
  };

  // 删除匹配
  const delete_match = (row, idx) => {
    console.log("删除行:", idx, row);
    let newList = JSON.parse(JSON.stringify(list_match));
    newList.splice(idx, 1);
    console.log(newList);
    setList_match(newList);
    setChoose_match_index(-1);
  };

  // 将匹配的信息提交到易触私库后台
  const push_match_goods = async () => {
    if (list_match.length == 0) {
      message.warning({
        content: "请添加至少一组数据",
      });
      return;
    }
    const newList = JSON.parse(JSON.stringify(list_match));
    for (let i = 0; i < newList.length; i++) {
      console.log("品牌信息:", newList[i].brand);
      newList[i].price_cent = Math.floor(newList[i].price * 100);
      if (newList[i].brand === undefined) {
        newList[i].brand = "other";
      }
    }
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      goods: newList,
    };
    console.log("提交的商品信息", newList);
    let res_ali = await post_axios("vision_mch_goods", "m_add", upMsg);
    if (res_ali) {
      message.success({
        content: t("common.add_scuuess"),
      });
      setList_match([]);
      setChoose_match_index(-1);
    }
  };

  const delete_goods = () => {
    if (clickRowKey === "") {
      message.warning({
        content: t("goods.choose_one_customer"),
      });
      return;
    }
    confirm({
      title: t("common.info"),
      icon: <ExclamationCircleFilled />,
      content: (
        <div>
          {t("goods.sure_to_delete_goods")}
          <strong> {clickRow.name}</strong>
        </div>
      ),
      onOk: async () => {
        let upMsg = {
          merchantSkuCode: clickRow.barcode,
          company_id: local_company_object.id,
          company: local_company_object.company,
          id: clickRow.id,
        };
        let res = await post_axios("vision_cloud_walk_goods", "m_del", upMsg);
        if (!res) return;
        message.success({
          content: t("common.delete_success"),
        });
        search_data();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("vision_mch_goods")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 110;
      setTableHeight(tableHeight);
      get_goods_brand();
    });
  }, []);
  return (
    <>
      <div className="vision_mch_goods modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_name")}</div>
            <Input
              placeholder=" "
              value={name_search}
              size="small"
              allowClear={true}
              onChange={(e) => setName_search(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_barcode")}</div>
            <Input
              placeholder=" "
              value={barcode_search}
              size="small"
              allowClear={true}
              onChange={(e) => setBarcode_search(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("common.status")}</div>
            <Select
              size="small"
              placeholder=" "
              value={status}
              onChange={(value) => setStatus(value)}
            >
              {Object.keys(kind_status).map((key) => {
                return (
                  <Option value={key} key={key}>
                    {text_check(kind_status[key])}
                  </Option>
                );
              })}
            </Select>
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={add_goods_dialog_show}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            id="page-child-table"
            style={{
              width: "99.9vw",
            }}
          >
            <Table
              dataSource={goods_list}
              size="small"
              bordered
              columns={columns}
              rowKey="barcode"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title={t("assets.select_product")}
        open={choose_goods_show}
        onCancel={() => setChoose_goods_show(false)}
        classNames={{
          body: "edit_dialog_body avm_status_dialog",
          wrapper: "noFooterFullscreen",
        }}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <div
          className="dialog_btn_box"
          style={{
            width: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-end",
            height: "40px",
            padding: "10px",
          }}
        >
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_name")}</div>
            <Input
              value={vision_name_search}
              onChange={(e) => setVision_name_search(e.target.value)}
              size="small"
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("goods.goods_barcode")}</div>
            <Input
              value={vision_barcode_search}
              onChange={(e) => setVision_barcode_search(e.target.value)}
              size="small"
            />
          </div>
          <Button
            size="small"
            shape="circle"
            icon={<SearchOutlined />}
            onClick={choose_goods_search}
          />
        </div>
        <Row>
          <Col span={16}>
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                height: "40px",
              }}
            >
              <Button type="primary" onClick={add_row_click}>
                添加行
              </Button>
              <Button
                type="primary"
                style={{ margin: "0 10px" }}
                onClick={push_match_goods}
              >
                加入私库
              </Button>

              <div className="add-goods-box">
                <span className="add-goods" style={{ fontSize: "16px" }}>
                  商品列表
                </span>
              </div>
            </div>
            <Table
              dataSource={list_match}
              size="small"
              bordered
              columns={listMatchColumns}
              rowKey="key"
              virtual
              scroll={{
                y: tableHeight + 40,
              }}
              onRow={(record) => {
                return {
                  onClick: () => handle_match_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (index == choose_match_index) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={false}
            />
          </Col>
          <Col span={8}>
            <div
              style={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                height: "40px",
              }}
            >
              <Group
                options={[
                  {
                    label: "支付宝总库",
                    value: "alipay",
                  },
                  {
                    label: "云从总库",
                    value: "cloudwalk",
                  },
                ]}
                onChange={(e) => choose_goods_kind_init(e.target.value)}
                defaultValue={radio_goods_kind}
                value={radio_goods_kind}
              ></Group>
            </div>
            <Table
              dataSource={vision_all_goods_list}
              size="small"
              bordered
              columns={visionGoodsColumns}
              rowKey={(record) =>
                record.barcode[0] + record.code_alipay
                  ? record.code_alipay
                  : record.code_cloudwalk
              }
              virtual
              scroll={{
                y: tableHeight + 40,
              }}
              onRow={(record) => {
                return {
                  onClick: () => row_click_goods_base(record), // 点击行
                };
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: goods_kind_page,
                defaultPageSize: goods_kind_rows,
                size: "small",
                current: goods_kind_page,
                total: goods_kind_total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: kindPageOnChange,
              }}
            />
          </Col>
        </Row>
      </Modal>
    </>
  );
}
